﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using HtmlAgilityPack;
using System.Diagnostics;
using AhgoraParser.Library.Dtos;
using AhgoraParser.Library.Enums;

namespace AhgoraParser.Library.Libs
{
    public class AhgoraWebCrawler
    {
        const string BaseUrl = "http://www.ahgora.com.br/";
        const string NOME_CAMPO_EMPRESA = "dados[empresa]";
        const string NOME_CAMPO_LOGIN = "dados[matricula]";
        const string NOME_CAMPO_SENHA = "dados[senha]";
        const string URL_AUTENTICAR = "batidas/entrar/ajax";
        const string URL_VISUALIZAR = "batidas/ver/";
        const string FPF_CODE = "a665612";
        string setCookieHeader;
        string htmlSite;
        public string HtmlSite
        {
            get { return htmlSite; }
            set { htmlSite = value; }
        }
        CookieContainer cookies;

        public delegate void MessageHandler(string msg);
        public delegate void RespostaRequisicao(string resposta);
        public event MessageHandler AoConseguirLogar;
        public event MessageHandler AoOcorrerFalha;
        public event RespostaRequisicao AoReceberHtmlPagina;

        public AhgoraWebCrawler()
        {
            cookies = new CookieContainer();
        }

        public void EfetuarLogin(string matricula, string senha)
        {
            try
            {
                // Create a request using a URL that can receive a post.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl+URL_AUTENTICAR);
                request.Method = "POST";
                string postData = string.Format("dados[empresa]={0}&dados[matricula]={1}&dados[senha]={2}",FPF_CODE,matricula,senha);
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                request.CookieContainer = cookies;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                AhgoraJsonResult result = JsonConvert.DeserializeObject<AhgoraJsonResult>( responseFromServer );

                if(result.r.Equals( StatusResultAuthentication.success )) 
                {
                    if (AoConseguirLogar != null)
                        AoConseguirLogar(htmlSite);
                } else
                {
                    AoOcorrerFalha(result.text);
                }
            }
            catch (Exception ex)
            {
                AoOcorrerFalha(ex.Message);
            }

        }

        public void GetHtml(string mesAno = null) 
        {
            try
            {
                if(mesAno == null)
                    mesAno = DateTime.Now.ToString( @"MM-yyyy" );
                // Create a request using a URL that can receive a post.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl + URL_VISUALIZAR+mesAno);
                request.Method = "GET";
                //request.ContentType = "text/plain;html";
                request.Accept = "*/*";
                request.CookieContainer = cookies;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string htmlSiteAhgora = reader.ReadToEnd();
                htmlSite = htmlSiteAhgora;
            }
            catch (Exception ex)
            {
                AoOcorrerFalha(ex.Message);
            }
        }
    }
}
